import React, { useState, useContext, useEffect, useRef } from "react";
import getConfig from "next/config";
import { useRouter } from "next/router";
import qs from "qs";
import styled, { keyframes, css } from "styled-components";
import { withAuthServerSideProps } from "../../utils/withAuth";
import SEO from "../../components/SEO";
import Text from "../../components/Text";
import Input from "../../components/Input";
import Button from "../../components/Button";
import Box from "../../components/Box";
import LocaleContext from "../../utils/LocaleContext";
import TorrentList from "../../components/TorrentList";
import { Search as SearchIcon } from "@styled-icons/boxicons-regular/Search";
import { TrendingUp } from "@styled-icons/boxicons-regular/TrendingUp";

// 动画效果
const fadeIn = keyframes`
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const scaleIn = keyframes`
  from {
    transform: scale(0.95);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
`;

const SearchContainer = styled.div`
  position: relative;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
`;

const SearchForm = styled.form`
  position: relative;
  display: flex;
  align-items: center;
  background: ${(props) => props.theme.colors.sidebar};
  border-radius: 12px;
  padding: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:focus-within {
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
`;

const StyledInput = styled(Input)`
  flex: 1;
  border: none;
  background: transparent;
  font-size: 1.1rem;
  padding: 12px 20px;

  &:focus {
    box-shadow: none;
  }
`;

const SearchButton = styled(Button)`
  padding: 12px 24px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
  }
`;

const SuggestionsContainer = styled.div`
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: ${(props) => props.theme.colors.sidebar};
  border-radius: 12px;
  margin-top: 8px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  z-index: 100;
  animation: ${fadeIn} 0.3s ease forwards;
`;

const SuggestionItem = styled.div`
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 12px;

  &:hover {
    background: ${(props) => props.theme.colors.background};
    transform: translateX(4px);
  }
`;

const TrendingIcon = styled(TrendingUp)`
  color: ${(props) => props.theme.colors.primary};
  width: 20px;
  height: 20px;
`;

const Search = ({ results, error, token }) => {
  const [torrents, setTorrents] = useState([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const searchRef = useRef(null);

  useEffect(() => {
    setTorrents(results?.torrents ?? []);
  }, [results?.total]);

  const router = useRouter();
  let {
    query: { query },
  } = router;
  query = query ? decodeURIComponent(query) : "";

  const {
    publicRuntimeConfig: { SQ_TORRENT_CATEGORIES, SQ_API_URL },
  } = getConfig();

  // 热门搜索建议
  const searchSuggestions = [
    "最新电影",
    "热门剧集",
    "经典动漫",
    "无损音乐",
    "高清纪录片",
    "游戏资源",
    "学习资料",
    "电子书",
  ];

  const handleSearch = (e) => {
    e.preventDefault();
    const form = new FormData(e.target);
    const query = form.get("query");
    if (query) {
      router.push(`/search/${encodeURIComponent(query)}`);
      setShowSuggestions(false);
    }
  };

  const handleSuggestionClick = (suggestion) => {
    setSearchValue(suggestion);
    if (searchRef.current) {
      searchRef.current.value = suggestion;
    }
    setShowSuggestions(false);
  };

  const { getLocaleString } = useContext(LocaleContext);

  return (
    <>
      <SEO
        title={
          query
            ? `${getLocaleString("searchSearchResults")} "${query}"`
            : `${getLocaleString("indexSearch")}`
        }
      />

      {/* 搜索区域 */}
      <Box
        mb={6}
        textAlign="center"
        css={css`
          animation: ${fadeIn} 0.5s ease forwards;
        `}
      >
        <Text as="h1" fontSize={4} fontWeight="bold" mb={3}>
          {query
            ? `${getLocaleString("searchSearchResults")} "${query}"`
            : `${getLocaleString("indexSearch")}`}
        </Text>

        <SearchContainer>
          <SearchForm onSubmit={handleSearch}>
            <StyledInput
              name="query"
              placeholder="输入关键词搜索..."
              ref={searchRef}
              value={searchValue}
              onChange={(e) => setSearchValue(e.target.value)}
              onFocus={() => setShowSuggestions(true)}
            />
            <SearchButton type="submit">
              <SearchIcon size={20} />
              {getLocaleString("indexSearch")}
            </SearchButton>
          </SearchForm>

          {showSuggestions && !query && (
            <SuggestionsContainer>
              <Text fontSize={1} color="grey" mb={3} fontWeight="bold">
                热门搜索
              </Text>
              {searchSuggestions.map((suggestion, index) => (
                <SuggestionItem
                  key={index}
                  onClick={() => handleSuggestionClick(suggestion)}
                >
                  <TrendingIcon />
                  <Text>{suggestion}</Text>
                </SuggestionItem>
              ))}
            </SuggestionsContainer>
          )}
        </SearchContainer>
      </Box>

      {/* 搜索结果 */}
      {error ? (
        <Text color="error">
          {getLocaleString("searchSearchError")}: {error}
        </Text>
      ) : (
        <>
          {query && (
            <>
              {torrents.length ? (
                <Box
                  css={css`
                    animation: ${fadeIn} 0.5s ease forwards;
                  `}
                >
                  <TorrentList
                    torrents={torrents}
                    setTorrents={setTorrents}
                    categories={SQ_TORRENT_CATEGORIES}
                    total={results.total}
                    fetchPath={`${SQ_API_URL}/torrent/search`}
                    token={token}
                  />
                </Box>
              ) : (
                <Text color="grey">{getLocaleString("catNoResults")}</Text>
              )}
            </>
          )}
        </>
      )}
    </>
  );
};

export const getServerSideProps = withAuthServerSideProps(
  async ({ token, fetchHeaders, query: { query, page: pageParam } }) => {
    if (!token || !query) return { props: {} };

    const {
      publicRuntimeConfig: { SQ_API_URL },
    } = getConfig();

    const params = {
      query: encodeURIComponent(query),
    };
    const page = pageParam ? parseInt(pageParam) : 0;
    if (page > 0) params.page = page;

    try {
      const searchRes = await fetch(
        `${SQ_API_URL}/torrent/search?${qs.stringify(params)}`,
        {
          headers: fetchHeaders,
        }
      );
      if (
        searchRes.status === 403 &&
        (await searchRes.text()) === "User is banned"
      ) {
        throw "banned";
      } else if (searchRes.status === 500) {
        const message = await searchRes.text();
        return { props: { error: message } };
      } else {
        const results = await searchRes.json();
        return { props: { results, token } };
      }
    } catch (e) {
      if (e === "banned") throw "banned";
      return { props: { results: { torrents: [] } } };
    }
  }
);

export default Search;
